package com.shaoshaohuo.app.ui.shipper;

import java.text.DecimalFormat;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMap.OnMapTouchListener;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.Polyline;
import com.amap.api.maps2d.model.PolylineOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.ui.EvaluationActivity;
import com.shaoshaohuo.app.ui.PhotoBrowseActivity;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.CarOption;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.db.DaoUtils;
import com.shaoshaohuo.app.entity.AddedService;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.CarTypeFirst;
import com.shaoshaohuo.app.entity.CarTypeSecond;
import com.shaoshaohuo.app.entity.Order.CarUserInfo;
import com.shaoshaohuo.app.entity.OrderDetail;
import com.shaoshaohuo.app.entity.OrderDetailEntity;
import com.shaoshaohuo.app.framework.ActivityCollector;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.adapter.AddedServiceSelectListAdapter;
import com.shaoshaohuo.app.utils.AreaUtil;
import com.shaoshaohuo.app.view.MeasureGridView;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.utils.AudioPlayManager;
import com.shaoshaohuo.app.utils.ImageLoadUtil;
import com.shaoshaohuo.app.utils.StringHelper;
/**
 * 物流订单详情
 * @author cao
 *
 */
public class OrderDetailShipperActivity extends BaseActivity implements OnClickListener, OnMapTouchListener {

    // 1 提醒货主支付，2提醒货主收货 ，3提醒司机响应
    private static final int REMIND_SHIPPER_PAY = 1;
    private static final int REMIND_SHIPPER_SURE = 2;
    private static final int REMIND_CAR_USER_SEND = 3;

    // -2 取消订单 5 确认装货 6 确认收货
    private static final int HANDLE_STATUS_CANCEL = -2;
    private static final int HANDLE_STATUS_LOADING = 5;
    private static final int HANDLE_STATUS_FINISH = 6;

    private TopbarView mTopbarView;

    private ScrollView mContentSv;

//    private MapView mapView;

    private TextView mZongjiaText;
    private TextView mYunfeiText;
    private TextView mBxfeiText;

    private TextView mShipperNameText;
    private TextView mPlaceOrderTimeText;
    private ImageView mCarUserHeadImage;
    private TextView mCarUserNameText;
    private TextView mCarUserPhoneText;
    private ImageView mCallPhoneImage;

    private TextView mStartCityText;
    private TextView mEndCityText;
//    private ImageView mAudioImage;
//    private TextView mStartAddrssText;
//    private TextView mEndAddressText;
    private TextView mSendTimeText;
    private TextView mReceiveTimeText;

    private TextView mCargoTypeText;
    private View mOrderImageLayout;
    private ImageView mPhoto1Image;
    private ImageView mPhoto2Image;
    private ImageView mPhoto3Image;
    private TextView mCarYaoqiuText;
    private TextView mMarkText;
    private TextView mYunshuLuxianText;

    private TextView mQiangCountText;
    private TextView mStatusText;
    private Button mLeftButton;
    private Button mFinishButton;

//    private MeasureGridView mAddedServiceGv;
    private View mCarUserInfoLayout;

    private String orderid;
    private AudioPlayManager audioPlayManager;

    private OrderDetail data;
    private TextView mZongLiChengText;
//    protected AMap aMap;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(new TopbarView(this));
        initData();
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                setContentView(R.layout.activity_order_detail_shipper);
                initView();
//                mapView = (MapView) findViewById(R.id.map);
//                mapView.onCreate(savedInstanceState); // 此方法必须重写
//                aMap = mapView.getMap();
                setUpView();

                requestData();
            }
        }, 200);
    }

    private void initData() {
        orderid = getIntent().getStringExtra(ExtraName.orderid);
        audioPlayManager = new AudioPlayManager(this);
    }

    private void requestData() {
        startLoadingDialog();
        RequestService.getInstance().getOrderDetail(this, orderid, OrderDetailEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    OrderDetailEntity entity = (OrderDetailEntity) resultData;
                    updateUi(entity);
                } else {
                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(msg);
            }
        });
    }

    protected void updateUi(OrderDetailEntity entity) {
        data = entity.getData();
        if (data == null) {
            showToast("无此订单!");
            finish();
            return;
        }

        mZongjiaText.setText("总费用：" + data.getTotal() + "元");
        mYunfeiText.setText("运费：" + data.getOrdertotal() + "元");
        mBxfeiText.setText("保险费用：" + data.getBxtotal() + "元");

        mShipperNameText.setText("货主：" + data.getShipperuserinfo().getRealname());
        mPlaceOrderTimeText.setText("下单时间：" + StringHelper.formatDateMinute(data.getCtime()));
        CarUserInfo caruserinfo = data.getCaruserinfo();
        if (caruserinfo != null) {
            // LoadUtils.getInstance().loadImage(mCarUserHeadImage, caruserinfo.getAvatar(), 0,
            // 100);
            ImageLoader.getInstance().displayImage(caruserinfo.getAvatar(), mCarUserHeadImage, ImageLoadUtil.getDisplayImageOptions(R.drawable.icon_default_headimage, 180));
            mCarUserNameText.setText(caruserinfo.getRealname());
            mCarUserPhoneText.setText(caruserinfo.getPhone());
            mCarUserPhoneText.setVisibility(View.GONE);
        }

        mStartCityText.setText(AreaUtil.getAreaFullname(data.getOrigincityid()) + data.getOriginaddress());
        mEndCityText.setText(AreaUtil.getAreaFullname(data.getReceivecityid()) + data.getReceiveaddress());
//        mStartAddrssText.setText(data.getOriginaddress());
//        mEndAddressText.setText(data.getReceiveaddress());
        mSendTimeText.setText(data.getOrigintime());
        mReceiveTimeText.setText(data.getReceivetime());

        /*mAudioImage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(data.getVoice())) {
                    showToast("无语音留言");
                } else {
                    if (!audioPlayManager.isPlaying()) {
                        audioPlayManager.startPlayingVoice(data.getVoice());
                    } else {
                        audioPlayManager.stopPlaying();
                        // audioPlayManager.startPlayingVoice(item.getVoice());
                    }
                }
            }
        });
*/
        if ("1".equals(data.getShipptype())) {
            mCargoTypeText.setText(CarOption.cargoItems[0]);
        } else if ("2".equals(data.getShipptype())) {
        	StringBuilder sb = new StringBuilder();
        	sb.append(CarOption.cargoItems[1] + "/" + data.getShippweight() + "kg");
        	if(Double.parseDouble(data.getShipparea())>0){
        		sb.append("/" + data.getShipparea() + "m³");
        	}
        	if(Double.parseDouble(data.getShipplength())>0){
        		sb.append("/" + data.getShipplength() + "m");
        	}
            mCargoTypeText.setText(sb.toString());
        } else if ("3".equals(data.getShipptype())) {
        	StringBuilder sb = new StringBuilder();
        	sb.append(CarOption.cargoItems[2] + "/" + data.getShipparea() + "m³");
        	if(Double.parseDouble(data.getShippweight())>0){
        		sb.append("/" + data.getShippweight() + "kg");
        	}
        	if(Double.parseDouble(data.getShipplength())>0){
        		sb.append("/" + data.getShipplength() + "m");
        	}
            mCargoTypeText.setText(sb.toString());
        	
//            mCargoTypeText.setText(CarOption.cargoItems[2] + "/" + Data.getShipparea() + "m³");
        }
        String[] shippimg = data.getShippimg();
        if (shippimg.length > 0) {
            mOrderImageLayout.setVisibility(View.VISIBLE);
            // LoadUtils.getInstance().loadImage(mPhoto1Image, shippimg[0]);
            ImageLoader.getInstance().displayImage(shippimg[0], mPhoto1Image, ImageLoadUtil.build);
            if (shippimg.length > 1) {
                // LoadUtils.getInstance().loadImage(mPhoto2Image, shippimg[1]);
                ImageLoader.getInstance().displayImage(shippimg[1], mPhoto2Image, ImageLoadUtil.build);
                if (shippimg.length > 2) {
                    // LoadUtils.getInstance().loadImage(mPhoto3Image, shippimg[2]);
                    ImageLoader.getInstance().displayImage(shippimg[2], mPhoto3Image, ImageLoadUtil.build);
                }
            }
        } else {
            mOrderImageLayout.setVisibility(View.GONE);
        }

//        AddedServiceSelectListAdapter<AddedService> serviceAdapter = new AddedServiceSelectListAdapter<>(this, data.getAttach(), false);
//        mAddedServiceGv.setAdapter(serviceAdapter);

        setCarRequire(data);

        mMarkText.setText(data.getMark());
        mYunshuLuxianText.setText((formatDouble(data.getTooriginDistance())) + "公里");
        mZongLiChengText.setText((formatDouble(data.getDistance())) + "公里");
//        initMap();

        mStatusText.setText(getStatusText(data.getStatus(), data.getCaruserstatus(), data.getShipperstatus(), data.getShipperdiscuss()));

        mQiangCountText.setText("已有" + data.getQiangCount() + "位司机抢单>>");

        if ("-1".equals(data.getCaruserstatus())) {
            mCallPhoneImage.setVisibility(View.GONE);
        } else {
            mCallPhoneImage.setVisibility(View.VISIBLE);
        }
    }

    public static String formatDouble(String text) {

        String format;
        try {
            DecimalFormat df = new DecimalFormat("0.0");
            double d = Double.parseDouble(text) / 1000;
            if (d <= 0) {
                d = 0;
            }
            format = df.format(d);
            return format;
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "0";
    }
/*
    private void initMap() {
       aMap.moveCamera(CameraUpdateFactory.zoomTo(4));
    	  //UiSettings uiSettings = aMap.getUiSettings();
          //uiSettings.setZoomControlsEnabled(true);
         // aMap.moveCamera(CameraUpdateFactory.zoomTo((float) (13.0)));
          //  uiSettings.setMyLocationButtonEnabled(true); // 是否显示默认的定位按钮
         // aMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层
    	

        if (!TextUtils.isEmpty(data.getOriginlat()) && !TextUtils.isEmpty(data.getOriginlng()) && !TextUtils.isEmpty(data.getReceivelat())
                        && !TextUtils.isEmpty(data.getReceivelng())) {
            double parseDouble = Double.parseDouble(data.getOriginlat());
            double parseDouble2 = Double.parseDouble(data.getOriginlng());
            double parseDouble3 = Double.parseDouble(data.getReceivelat());
            double parseDouble4 = Double.parseDouble(data.getReceivelng());
            Polyline addPolyline = aMap
                            .addPolyline((new PolylineOptions()).add(new LatLng(parseDouble, parseDouble2), new LatLng(parseDouble3, parseDouble4))
                                            .width(5).color(Color.parseColor("#ff6368")));
        }

        // CameraPosition cameraPosition = aMap.getCameraPosition();

        if (!TextUtils.isEmpty(data.getPushlat()) && !TextUtils.isEmpty(data.getPushlng())) {
            double lat = Double.parseDouble(data.getPushlat());
            double lng = Double.parseDouble(data.getPushlng());
            MarkerOptions markerOption = new MarkerOptions();
            markerOption.title("司机位置");
            markerOption.draggable(true);
            markerOption.position(new LatLng(lat, lng));
            aMap.addMarker(markerOption).showInfoWindow();
        }

        aMap.setOnMapTouchListener(this);

    }*/

    @Override
    public void onTouch(MotionEvent motionEvent) {
        int action = motionEvent.getAction();
        switch (action) {
        case MotionEvent.ACTION_UP:
            mContentSv.requestDisallowInterceptTouchEvent(false);
            break;
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
            mContentSv.requestDisallowInterceptTouchEvent(true);
            break;
        }
    }

    private void setCarRequire(OrderDetail data) {
        String cartype = data.getCartype();
        String carcid = data.getCarcid();
        int carweight = Integer.parseInt(data.getCarweight());
        int carlength = Integer.parseInt(data.getCarlength());
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(cartype) && !TextUtils.isEmpty(carcid)) {
            List<CarTypeFirst> findAllCartype = DaoUtils.findAllCartype();
            CarTypeFirst carTypeFirst = null;
            CarTypeSecond carTypeSecond = null;
            for (CarTypeFirst type : findAllCartype) {
                if (type.getTypeid().equals(cartype)) {
                    carTypeFirst = type;
                    break;
                }
            }
            if (carTypeFirst != null) {
                List<CarTypeSecond> data2 = carTypeFirst.getData();
                for (CarTypeSecond type : data2) {
                    if (carcid.equals(type.getCid())) {
                        carTypeSecond = type;
                        break;
                    }
                }
            }
            if (carTypeSecond != null) {
                sb.append(carTypeSecond.getName());
            }
        }
        if (carweight > 0) {
            sb.append("/" + CarOption.carWeightItems[carweight - 1]);
        }
        if (carlength > 0) {
            sb.append("/" + CarOption.carLongItems[carlength - 1]);
        }
        mCarYaoqiuText.setText(sb.toString());
    }

    private String getStatusText(String status, String carStatus, String userStatus, String shipperdiscuss) {
        switch (Integer.parseInt(status)) {
        case -4:
            mTopbarView.setRightText("");
            mLeftButton.setVisibility(View.GONE);
            mFinishButton.setVisibility(View.GONE);

            mQiangCountText.setVisibility(View.GONE);
            mCarUserInfoLayout.setVisibility(View.VISIBLE);
            return "货主拒绝";
        case -3:
            mTopbarView.setRightText("");
            mLeftButton.setVisibility(View.GONE);
            mFinishButton.setVisibility(View.GONE);

            mQiangCountText.setVisibility(View.GONE);
            mCarUserInfoLayout.setVisibility(View.VISIBLE);
            return "订单失效";
        case -2:
            mTopbarView.setRightText("");
            mLeftButton.setVisibility(View.GONE);
            mFinishButton.setVisibility(View.GONE);

            mQiangCountText.setVisibility(View.GONE);
            mCarUserInfoLayout.setVisibility(View.VISIBLE);
            return "货主取消订单";
        case -1:
            mTopbarView.setRightText("");
            mLeftButton.setVisibility(View.GONE);
            mFinishButton.setVisibility(View.GONE);

            mQiangCountText.setVisibility(View.GONE);
            mCarUserInfoLayout.setVisibility(View.VISIBLE);
            return "车主拒绝";
        case 1:
            if ("2".equals(userStatus)) {
                mTopbarView.setRightText("取消订单");
                mLeftButton.setVisibility(View.GONE);
                mFinishButton.setVisibility(View.GONE);
                mQiangCountText.setVisibility(View.VISIBLE);
                mCarUserInfoLayout.setVisibility(View.GONE);

                mTopbarView.setRightClickListener(cancelOrderListener);
                return "抢单中";
            } else if ("3".equals(userStatus)) {
                mTopbarView.setRightText("取消订单");
                mLeftButton.setVisibility(View.GONE);
                mFinishButton.setVisibility(View.VISIBLE);
                mQiangCountText.setVisibility(View.GONE);
                mCarUserInfoLayout.setVisibility(View.VISIBLE);

                mFinishButton.setText("立即支付");
                mTopbarView.setRightClickListener(cancelOrderListener);
                mFinishButton.setOnClickListener(immediatelyPayListener);
                return "待支付";
            }
            break;
        case 2:
            if ("1".equals(carStatus) && "3".equals(userStatus)) {
                mTopbarView.setRightText("取消订单");
                mLeftButton.setVisibility(View.GONE);
                mFinishButton.setVisibility(View.VISIBLE);
                mQiangCountText.setVisibility(View.GONE);
                mCarUserInfoLayout.setVisibility(View.VISIBLE);

                mFinishButton.setText("提醒司机响应");
                mTopbarView.setRightClickListener(cancelOrderListener);
                mFinishButton.setOnClickListener(remindCarUserListener);
                return "等待司机响应";
            }
            break;
        case 3:
            mTopbarView.setRightText("取消订单");
            mLeftButton.setVisibility(View.GONE);
            mFinishButton.setVisibility(View.VISIBLE);
            mQiangCountText.setVisibility(View.GONE);
            mCarUserInfoLayout.setVisibility(View.VISIBLE);

            mFinishButton.setText("立即支付");
            mTopbarView.setRightClickListener(cancelOrderListener);
            mFinishButton.setOnClickListener(immediatelyPayListener);
            return "待支付";
        case 4:
            if ("3".equals(userStatus)) {
                mTopbarView.setRightText("取消订单");
                mLeftButton.setVisibility(View.GONE);
                mFinishButton.setVisibility(View.VISIBLE);
                mQiangCountText.setVisibility(View.GONE);
                mCarUserInfoLayout.setVisibility(View.VISIBLE);

                mFinishButton.setText("立即支付");
                mTopbarView.setRightClickListener(cancelOrderListener);
                mFinishButton.setOnClickListener(immediatelyPayListener);
                return "待支付";
            }
            break;
        case 5:
            if ("4".equals(userStatus)) {
                mTopbarView.setRightText("取消订单");
                mLeftButton.setVisibility(View.GONE);
                mFinishButton.setVisibility(View.VISIBLE);
                mQiangCountText.setVisibility(View.GONE);
                mCarUserInfoLayout.setVisibility(View.VISIBLE);

                mFinishButton.setText("装货完毕");
                mTopbarView.setRightClickListener(cancelOrderListener);
                mFinishButton.setOnClickListener(loadingListener);
                return "待装货";
            } else {
                mTopbarView.setRightText("取消订单");
                mLeftButton.setVisibility(View.GONE);
                mFinishButton.setVisibility(View.VISIBLE);
                mQiangCountText.setVisibility(View.GONE);
                mCarUserInfoLayout.setVisibility(View.VISIBLE);

                mFinishButton.setText("提醒司机确认");
                mTopbarView.setRightClickListener(remindCarUserListener);
                mFinishButton.setOnClickListener(loadingListener);
                return "已装货";
            }
        case 6:
            if ("5".equals(userStatus)) {
                mTopbarView.setRightText("");
                mLeftButton.setVisibility(View.GONE);
                mFinishButton.setVisibility(View.VISIBLE);
                mQiangCountText.setVisibility(View.GONE);
                mCarUserInfoLayout.setVisibility(View.VISIBLE);

                mFinishButton.setText("确认送达");
                mFinishButton.setOnClickListener(finishListener);
                return "运输中";
            } else {
                mTopbarView.setRightText("");
                mLeftButton.setVisibility(View.GONE);
                mFinishButton.setVisibility(View.VISIBLE);
                mQiangCountText.setVisibility(View.GONE);
                mCarUserInfoLayout.setVisibility(View.VISIBLE);

                mFinishButton.setText("提醒司机确认");
                mFinishButton.setOnClickListener(remindCarUserListener);
                return "已送达";
            }
        case 7:
            if ("1".equals(shipperdiscuss)) {
                mTopbarView.setRightText("");
                mLeftButton.setVisibility(View.GONE);
                mFinishButton.setVisibility(View.VISIBLE);
                mQiangCountText.setVisibility(View.GONE);
                mCarUserInfoLayout.setVisibility(View.VISIBLE);

                mFinishButton.setText("评价");
                mFinishButton.setOnClickListener(evaluationListener);
                return "已完成,未评价";
            } else {
                mTopbarView.setRightText("");
                mLeftButton.setVisibility(View.GONE);
                mFinishButton.setVisibility(View.VISIBLE);
                mQiangCountText.setVisibility(View.GONE);
                mCarUserInfoLayout.setVisibility(View.VISIBLE);

                mFinishButton.setText("已评价");
                mFinishButton.setEnabled(false);
                return "已完成,已评价";
            }
        default:
            mTopbarView.setRightText("");
            mLeftButton.setVisibility(View.GONE);
            mFinishButton.setVisibility(View.GONE);
            mQiangCountText.setVisibility(View.GONE);
            mCarUserInfoLayout.setVisibility(View.GONE);
            break;
        }
        return "";
    }

    @SuppressLint("CutPasteId")
    private void initView() {
        mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

        mContentSv = (ScrollView) this.findViewById(R.id.sv_content);

        mQiangCountText = (TextView) this.findViewById(R.id.textview_qiang_count);
        mStatusText = (TextView) this.findViewById(R.id.textview_status);
        mLeftButton = (Button) this.findViewById(R.id.button_left);
        mFinishButton = (Button) this.findViewById(R.id.button_finish);

        mZongjiaText = (TextView) this.findViewById(R.id.textview_zongjia);
        mYunfeiText = (TextView) this.findViewById(R.id.textview_yunfei);
        mBxfeiText = (TextView) this.findViewById(R.id.textview_baoxianfeiyong);

        mStartCityText = (TextView) this.findViewById(R.id.textview_start_city);
        mEndCityText = (TextView) this.findViewById(R.id.textview_end_city);
//        mAudioImage = (ImageView) this.findViewById(R.id.imageview_play_audio);
//        mStartAddrssText = (TextView) this.findViewById(R.id.textview_start_address);
//        mEndAddressText = (TextView) this.findViewById(R.id.textview_end_address);
        mSendTimeText = (TextView) this.findViewById(R.id.textview_send_time);
        mReceiveTimeText = (TextView) this.findViewById(R.id.textview_receive_time);

        mOrderImageLayout = this.findViewById(R.id.layout_order_image);
        mShipperNameText = (TextView) this.findViewById(R.id.textview_shipper_name);
        mPlaceOrderTimeText = (TextView) this.findViewById(R.id.textview_place_order_time);

        mCarUserHeadImage = (ImageView) this.findViewById(R.id.imageview_car_user_headview);
        mCarUserNameText = (TextView) this.findViewById(R.id.textview_car_username);
        mCarUserPhoneText = (TextView) this.findViewById(R.id.textview_car_phone);
        mCallPhoneImage = (ImageView) this.findViewById(R.id.imageview_call_phone);

        mCargoTypeText = (TextView) this.findViewById(R.id.textview_cargo_type);
        mPhoto1Image = (ImageView) this.findViewById(R.id.imageview_photo1);
        mPhoto2Image = (ImageView) this.findViewById(R.id.imageview_photo2);
        mPhoto3Image = (ImageView) this.findViewById(R.id.imageview_photo3);
        mCarYaoqiuText = (TextView) this.findViewById(R.id.textview_car_yaoqiu);
        mMarkText = (TextView) this.findViewById(R.id.textview_mark);
        mYunshuLuxianText = (TextView) this.findViewById(R.id.textview_zhuanghuojuli);
        mZongLiChengText = (TextView) this.findViewById(R.id.textview_zonglicheng);

//        mAddedServiceGv = (MeasureGridView) this.findViewById(R.id.gv_service_list);

        mCarUserInfoLayout = this.findViewById(R.id.layout_my_info);
    }

    private void setUpView() {
        mTopbarView.setCenterText("订单详情");
        mTopbarView.setLeftView(true, true);

        mQiangCountText.setVisibility(View.GONE);

        mQiangCountText.setOnClickListener(this);
        mCallPhoneImage.setOnClickListener(this);

        mPhoto1Image.setOnClickListener(this);
        mPhoto2Image.setOnClickListener(this);
        mPhoto3Image.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.textview_qiang_count:
            Intent intent1 = new Intent(this, SelectDriverActivity.class);
            intent1.putExtra(ExtraName.orderid, orderid);
            intent1.putExtra(ExtraName.startCity, mStartCityText.getText().toString());
            intent1.putExtra(ExtraName.endCity, mEndCityText.getText().toString());
            intent1.putExtra(ExtraName.cargoType, mCargoTypeText.getText().toString());
            startActivity(intent1);
            break;
        case R.id.imageview_call_phone:
            callCarUser();
            break;
        case R.id.imageview_photo1:
            if (data != null && data.getShippimg().length > 0) {
                Intent intent = new Intent(this, PhotoBrowseActivity.class);
                intent.putExtra(ExtraName.photoArray, data.getShippimg());
                intent.putExtra(ExtraName.photoIndex, 0);
                startActivity(intent);
            }
            break;
        case R.id.imageview_photo2:
            if (data != null && data.getShippimg().length > 1) {
                Intent intent = new Intent(this, PhotoBrowseActivity.class);
                intent.putExtra(ExtraName.photoArray, data.getShippimg());
                intent.putExtra(ExtraName.photoIndex, 1);
                startActivity(intent);
            }
            break;
        case R.id.imageview_photo3:
            if (data != null && data.getShippimg().length > 2) {
                Intent intent = new Intent(this, PhotoBrowseActivity.class);
                intent.putExtra(ExtraName.photoArray, data.getShippimg());
                intent.putExtra(ExtraName.photoIndex, 2);
                startActivity(intent);
            }
            break;
        }
    }

    private void callCarUser() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("确定呼叫车主 " + data.getCaruserinfo().getRealname() + "?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + data.getCaruserinfo().getPhone()));
                startActivity(intent);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }

    private void remindOrder() {
        startLoadingDialog();
        RequestService.getInstance().remindOrder(this, orderid, REMIND_CAR_USER_SEND + "", BaseEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    showToast("提醒成功");
                } else {
                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(msg);
            }
        });
    }

    private void orderProcess(final int status) {
        startLoadingDialog();
        RequestService.getInstance().orderProcessShipper(this, orderid, status + "", BaseEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    switch (status) {
                    case HANDLE_STATUS_CANCEL:
                        showToast("订单已取消");
                        break;
                    case HANDLE_STATUS_LOADING:
                        showToast("确认装货成功");
                        break;
                    case HANDLE_STATUS_FINISH:
                        showToast("确认收货成功");
                        break;
                    }
                    requestData();
                } else {
                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(msg);
            }
        });
    }

    /**
     * 取消订单
     */
    private OnClickListener cancelOrderListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            showProcessDialog("确认取消订单?", HANDLE_STATUS_CANCEL);
        }
    };
    /**
     * 装货完毕
     */
    private OnClickListener loadingListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            showProcessDialog("确认装货完毕?", HANDLE_STATUS_LOADING);
        }
    };
    /**
     * 确认送达
     */
    private OnClickListener finishListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            showProcessDialog("确认货物送达?", HANDLE_STATUS_FINISH);
        }
    };
    /**
     * 立即支付
     */
    private OnClickListener immediatelyPayListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(OrderDetailShipperActivity.this, PayOrderActivity.class);
            intent.putExtra(ExtraName.orderid, orderid);
            startActivity(intent);
        }
    };
    /**
     * 提醒司机响应
     */
    private OnClickListener remindCarUserListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            remindOrder();
        }
    };

    /**
     * 评价
     */
    private OnClickListener evaluationListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(OrderDetailShipperActivity.this, EvaluationActivity.class);
            intent.putExtra(ExtraName.orderid, orderid);
            startActivity(intent);
        }
    };

    protected void showProcessDialog(String message, final int status) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                orderProcess(status);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create().show();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
      /*  if (mapView != null) {
            mapView.onResume();
        }*/
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
//        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
//        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mapView.onDestroy();
        if (audioPlayManager.isPlaying()) {
            audioPlayManager.stopPlaying();
        }
    }
    
    @Override
    public void finish() {
    	if(ActivityCollector.activities.size()==1){
    		Intent launchIntent = getPackageManager().
                    getLaunchIntentForPackage(getPackageName());
    		startActivity(launchIntent);
    	}
    	super.finish();
    }

}
